/*************************************************************************
	> File Name: test6.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/19 19:54
 ************************************************************************/

#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <cassert>

static void handler(int signum)
{
    std::cout << "Catch signal:" << signum << std::endl;
}

static void showPending(sigset_t &pending)
{
    for (int sig = 1; sig <= 31; sig++) {
        if (sigismember(&pending, sig)) {
            std::cout << 1;
        } else {
            std::cout << 0;
        }
    }
    std::cout << std::endl;
}

int main(int argc, char *argv[])
{
    signal(2, handler);
    sigset_t bset, obset;
    sigset_t pending;
    sigemptyset(&bset);
    sigemptyset(&obset);
    sigemptyset(&pending);
    sigaddset(&bset, 2);
    int n = sigprocmask(SIG_BLOCK, &bset, &obset);
    assert(n == 0);
    (void)n;
    std::cout << "Block the signal of 2 success, pid:" << getpid() << std::endl;
    int count = 0;
    while (1) {
        sigpending(&pending);
        showPending(pending);
        sleep(1);
        ++count;
        if (count == 20) {
            std::cout << "Free the block of 2 signal." << std::endl;
            int n = sigprocmask(SIG_SETMASK, &obset, nullptr);
            assert(n == 0);
            (void)n;
        }
    }
    return 0;
}
